package com.example.aiquestions.service;

import com.example.aiquestions.model.ChatSession;
import org.springframework.stereotype.Service;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class ChatSessionService {
    private static final long SESSION_EXPIRATION_MINUTES = 30;
    private final Map<String, ChatSession> sessions = new ConcurrentHashMap<>();
    
    public ChatSession createSession(String provider) {
        String sessionId = UUID.randomUUID().toString();
        ChatSession session = new ChatSession(sessionId, provider);
        sessions.put(sessionId, session);
        return session;
    }
    
    public ChatSession getSession(String sessionId) {
        ChatSession session = sessions.get(sessionId);
        if (session != null) {
            session.updateLastAccessTime();
        }
        return session;
    }
    
    @Scheduled(fixedRate = 300000) // 每5分钟执行一次
    public void cleanExpiredSessions() {
        sessions.entrySet().removeIf(entry -> 
            entry.getValue().isExpired(SESSION_EXPIRATION_MINUTES));
    }
    
    public void removeSession(String sessionId) {
        sessions.remove(sessionId);
    }
    
    public void initializeSession(String sessionId, String basePrompt) {
        ChatSession session = sessions.get(sessionId);
        if (session != null) {
            session.setBasePrompt(basePrompt);
            session.setInitialized(true);
            session.updateLastAccessTime();
        }
    }
} 